package com.dms.modules.order.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.exception.BusinessException;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.order.dto.OrderSubmitDTO;
import com.dms.modules.order.entity.Order;
import com.dms.modules.order.service.OrderService;
import com.dms.modules.order.vo.OrderDetailVO;
import com.dms.modules.order.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/v1/orders")
@Api(tags = "订单接口")
@Validated
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        return SecurityUtils.getCurrentUserId();
    }

    @PostMapping("/submit")
    @ApiOperation("统一下单接口")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<List<Long>> submitOrder(@RequestBody @Valid OrderSubmitDTO submitDTO) {
        try {
            Long userId = getCurrentUserId();
            List<Long> orderIds = orderService.submitOrder(userId, submitDTO);
            return ApiResponse.success(orderIds);
        } catch (BusinessException e) {
            log.warn("提交订单失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("提交订单失败", e);
            return ApiResponse.error("提交订单失败");
        }
    }

    @PostMapping("/{id}/cancel")
    @ApiOperation("取消订单")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<Boolean> cancelOrder(
            @ApiParam("订单ID") @PathVariable("id") @NotNull(message = "订单ID不能为空") Long id,
            @ApiParam("取消原因") @RequestParam @NotBlank(message = "取消原因不能为空") String reason) {
        try {
            Long userId = getCurrentUserId();
            boolean result = orderService.cancelOrder(userId, id, reason);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.warn("取消订单失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return ApiResponse.error("取消订单失败");
        }
    }

    @GetMapping
    @ApiOperation("获取订单列表")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<IPage<OrderVO>> getOrders(
            @ApiParam("页码") @RequestParam(defaultValue = "1") @Min(value = 1, message = "页码必须大于0") Integer pageNum,
            @ApiParam("每页条数") @RequestParam(defaultValue = "10") @Min(value = 1, message = "每页条数必须大于0") Integer pageSize,
            @ApiParam("订单状态") @RequestParam(required = false) Integer status) {
        try {
            Long userId = getCurrentUserId();
            Page<Order> page = new Page<>(pageNum, pageSize);
            IPage<OrderVO> orders = orderService.getUserOrders(page, userId, status);
            return ApiResponse.success(orders);
        } catch (BusinessException e) {
            log.warn("获取订单列表失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取订单列表失败", e);
            return ApiResponse.error("获取订单列表失败");
        }
    }

    @GetMapping("/{id}")
    @ApiOperation("获取订单详情")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN', 'MERCHANT')")
    public ApiResponse<OrderDetailVO> getOrderDetail(
            @ApiParam("订单ID") @PathVariable("id") @NotNull(message = "订单ID不能为空") Long id) {
        try {
            Long userId = getCurrentUserId();
            OrderDetailVO orderDetail = orderService.getOrderDetail(userId, id);
            return ApiResponse.success(orderDetail);
        } catch (BusinessException e) {
            log.warn("获取订单详情失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return ApiResponse.error("获取订单详情失败");
        }
    }

    @PostMapping("/{id}/confirm")
    @ApiOperation("确认收货")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<Boolean> confirmReceipt(
            @ApiParam("订单ID") @PathVariable("id") @NotNull(message = "订单ID不能为空") Long id) {
        try {
            Long userId = getCurrentUserId();
            boolean result = orderService.confirmReceipt(userId, id);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.warn("确认收货失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("确认收货失败", e);
            return ApiResponse.error("确认收货失败");
        }
    }

    @PostMapping("/{id}/refund")
    @ApiOperation("申请退款")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<Long> applyRefund(
            @ApiParam("订单ID") @PathVariable("id") @NotNull(message = "订单ID不能为空") Long id,
            @ApiParam("退款原因") @RequestParam @NotBlank(message = "退款原因不能为空") String reason) {
        try {
            Long userId = getCurrentUserId();
            Long refundId = orderService.applyRefund(userId, id, reason);
            return ApiResponse.success(refundId);
        } catch (BusinessException e) {
            log.warn("申请退款失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("申请退款失败", e);
            return ApiResponse.error("申请退款失败");
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除订单")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<Boolean> deleteOrder(
            @ApiParam("订单ID") @PathVariable("id") @NotNull(message = "订单ID不能为空") Long id) {
        try {
            Long userId = getCurrentUserId();
            boolean result = orderService.deleteOrder(userId, id);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.warn("删除订单失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("删除订单失败", e);
            return ApiResponse.error("删除订单失败");
        }
    }

    @GetMapping("/unpaid")
    @ApiOperation("获取待付款订单列表")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<IPage<OrderVO>> getUnpaidOrders(
            @RequestParam(defaultValue = "1") @Min(1) Integer pageNum,
            @RequestParam(defaultValue = "10") @Min(1) Integer pageSize) {
        try {
            Long userId = getCurrentUserId();
            Page<Order> page = new Page<>(pageNum, pageSize);
            IPage<OrderVO> orders = orderService.getUserOrders(page, userId, 0); // 0-待付款
            return ApiResponse.success(orders);
        } catch (Exception e) {
            log.error("获取待付款订单列表失败", e);
            return ApiResponse.error("获取待付款订单列表失败");
        }
    }

    @GetMapping("/unshipped")
    @ApiOperation("获取待发货订单列表")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<IPage<OrderVO>> getUnshippedOrders(
            @RequestParam(defaultValue = "1") @Min(1) Integer pageNum,
            @RequestParam(defaultValue = "10") @Min(1) Integer pageSize) {
        try {
            Long userId = getCurrentUserId();
            Page<Order> page = new Page<>(pageNum, pageSize);
            IPage<OrderVO> orders = orderService.getUserOrders(page, userId, 1); // 1-待发货
            return ApiResponse.success(orders);
        } catch (Exception e) {
            log.error("获取待发货订单列表失败", e);
            return ApiResponse.error("获取待发货订单列表失败");
        }
    }

    @GetMapping("/unreceived")
    @ApiOperation("获取待收货订单列表")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<IPage<OrderVO>> getUnreceivedOrders(
            @RequestParam(defaultValue = "1") @Min(1) Integer pageNum,
            @RequestParam(defaultValue = "10") @Min(1) Integer pageSize) {
        try {
            Long userId = getCurrentUserId();
            Page<Order> page = new Page<>(pageNum, pageSize);
            IPage<OrderVO> orders = orderService.getUserOrders(page, userId, 2); // 2-待收货
            return ApiResponse.success(orders);
        } catch (Exception e) {
            log.error("获取待收货订单列表失败", e);
            return ApiResponse.error("获取待收货订单列表失败");
        }
    }
} 